<template>
  <div v-if="!item.hidden&&item.children">

    <!-- 无孩子 -->
    <router-link v-if="item.children.length === 0" :to="resolvePath(item.path)">
      <el-menu-item :index="resolvePath(item.path)" :class="{'submenu-title-noDropdown':!isNest}" class="isLeaf">
        <img v-if="item.meta" :src="require('@/assets/' + item.meta + '.png')" />
        <span v-if="item.name" slot="title">{{item.name}}</span>
      </el-menu-item>
    </router-link>

    <!-- 有且仅有一个需要显示在侧边栏的菜单 -->
    <router-link v-else-if="hasOneShowingChild(item.children)" :to="resolvePath(onlyOneChild.path)">
      <el-menu-item :index="resolvePath(onlyOneChild.path)" :class="{'submenu-title-noDropdown':!isNest}" class="isLeaf">
        <img v-if="item.meta" :src="require('@/assets/' + item.meta + '.png')" />
        <span v-if="item.name" slot="title">{{item.name}}</span>
      </el-menu-item>
    </router-link>

    <!-- 不仅有一个需要显示在侧边栏的菜单 -->
    <el-submenu v-else :index="item.name||item.path">
      <template slot="title">
        <img v-if="item.meta" :src="require('@/assets/' + item.meta + '.png')" />
        <span v-if="item.name" slot="title">{{item.name}}</span>
      </template>

      <template v-for="child in item.children" v-if="!child.hidden">
        <sidebar-item :is-nest="true" class="nest-menu" v-if="child.children&&child.children.length>0" :item="child" :key="child.path" :base-path="resolvePath(child.path)"></sidebar-item>
        <router-link v-else :to="resolvePath(child.path)" :key="child.name">
          <el-menu-item :index="resolvePath(child.path)" class="leaf-menu">
            <span v-if="child.name" slot="title">{{child.name}}</span>
          </el-menu-item>
        </router-link>
      </template>
    </el-submenu>

  </div>
</template>

<script>
  import path from 'path'

  export default {
    name: 'SidebarItem',
    props: {
      // route配置json
      item: {
        type: Object,
        required: true
      },
      isNest: {
        type: Boolean,
        default: false
      },
      basePath: {
        type: String,
        default: ''
      }
    },
    data () {
      return {
        onlyOneChild: null
      }
    },
    methods: {
      hasOneShowingChild (children) {
        const showingChildren = children.filter(item => {
          if (item.hidden) {
            return false
          } else {
            this.onlyOneChild = item
            return true
          }
        })
        if (showingChildren.length === 1) {
          return true
        }
        return false
      },
      resolvePath (...paths) {
        const routers = path.resolve(this.basePath, ...paths)
        return routers
      }
    }
  }
</script>
